/**
 * @description: 时间函数工具类
 * @author: lxz
 * @update: lxz(2021-01-18)
 */

/**
 * 时间转化为年 月 日 时 分 秒
 * @param {string|number}  time   传入时间
 * @param {string=}        format 返回格式，支持自定义，但参数必须与formateArr里保持一致
 * @return {string}               返回格式化后的时间字符串
 */
export function formatDate(time, format = 'Y/M/D h:m:s') {
	// 数据转化
	const formatNumber = n => {
		n = n.toString()
		return n[1] ? n : '0' + n
	}
	const formateArr = ['Y', 'M', 'D', 'W', 'h', 'm', 's']
	const WeekArr = ['天', '一', '二', '三', '四', '五', '六']
	const returnArr = []

	const date = new Date(time)
	returnArr.push(date.getFullYear())
	returnArr.push(formatNumber(date.getMonth() + 1))
	returnArr.push(formatNumber(date.getDate()))

	returnArr.push(WeekArr[date.getDay()])

	returnArr.push(formatNumber(date.getHours()))
	returnArr.push(formatNumber(date.getMinutes()))
	returnArr.push(formatNumber(date.getSeconds()))

	returnArr.forEach((val, key) => {
		format = format.replace(formateArr[key], val)
	})
	return format
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatDateTxt(time, option) {
	if (('' + time).length === 10) {
		time = parseInt(time) * 1000
	} else {
		time = +time
	}
	const d = new Date(time)
	const now = Date.now()

	const diff = (now - d) / 1000

	if (diff < 30) {
		return '刚刚'
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + '分钟前'
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + '小时前'
	} else if (diff < 3600 * 24 * 2) {
		return '1天前'
	}
	if (option) {
		return formatDate(time, option)
	} else {
		return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
	}
}
